package com.reggie.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.reggie.module.entity.po.Employee;
import com.reggie.module.entity.po.User;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 早睡蛋
 * @Date 2022/7/15 18:51:22
 * @Desc:
 */
public class JWTUtil {
    private static String TOKEN = "hzcc_takeout"; //密钥

    /**
     * 使用JWT生成token
     */
    public static String createUserToken(User user) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_WEEK, 1);
        String token = JWT.create()
                .withClaim("id", user.getId())
                .withClaim("phone", user.getPhone())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(TOKEN));
        return token;
    }

    /**
     * 使用JWT生成token
     */
    public static String createEmpToken(Employee employee) {
        Long id = employee.getId();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_WEEK, 1);
        String token = JWT.create()
                .withClaim("id", id)
                .withClaim("username", employee.getUsername())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(TOKEN));
        return token;
    }

    /**
     * 验证token信息
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    public static boolean verify2(String token) {
        Algorithm algorithm = Algorithm.HMAC256(TOKEN);
        JWTVerifier verifier = JWT.require(algorithm)
                .build();
        verifier.verify(token);
        return true;
    }

    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 验证token信息
     */
    public static Map<String, Object> verifyEmp(String token) {
        Map<String, Object> map = new HashMap<>();
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN)).build();
            DecodedJWT verify = jwtVerifier.verify(token);
            Long id = verify.getClaims().get("id").asLong();
            String username = verify.getClaims().get("username").asString();
            System.out.println("id:" + id + "   username:" + username);
            map.put("id", id);
            map.put("username", username);

        } catch (Exception e) {
            map.put("error", "token错误");
            throw new RuntimeException(e);
        }
        return map;
    }
}
